package com.automailerbot.registration;

import com.automailerbot.utils.WebDriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class OutlookRegisterService {

    public void registerAccount(String username, String password) throws Exception {
        WebDriver driver = (WebDriver) WebDriverFactory.createDriver();

        try {
            driver.get("https://signup.live.com/");

            // 输入用户名
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            WebElement usernameInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[type='email']")));
            usernameInput.sendKeys(username);
            driver.findElement(By.id("iSignupAction")).click();
            Thread.sleep(2000);

            // 设置密码
            WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(10));
            WebElement passField = wait1.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[type='password']")));
            passField.sendKeys(password);
            driver.findElement(By.id("iSignupAction")).click();
            Thread.sleep(2000);

            // 输入姓名
            WebElement firstName = driver.findElement(By.name("FirstName"));
            WebElement lastName = driver.findElement(By.name("LastName"));
            firstName.sendKeys("Auto");
            lastName.sendKeys("Bot");
            driver.findElement(By.id("iSignupAction")).click();
            Thread.sleep(2000);

            // 设置生日
            WebElement country = driver.findElement(By.name("Country"));
            WebElement birthMonth = driver.findElement(By.name("BirthMonth"));
            WebElement birthDay = driver.findElement(By.name("BirthDay"));
            WebElement birthYear = driver.findElement(By.name("BirthYear"));
            country.sendKeys("China");
            birthMonth.sendKeys("January");
            birthDay.sendKeys("1");
            birthYear.sendKeys("1990");
            driver.findElement(By.id("iSignupAction")).click();
            Thread.sleep(3000);

            // 等待验证码页面加载
            // 接入验证码识别（2Captcha）——代码预留
            System.out.println("等待验证码输入（图形验证码 / 手机验证）...");

            // 用户手动输入验证码或接入自动处理模块后继续

            // 提交完成
            System.out.println("✅ 注册流程完成，请确认验证流程");
            Thread.sleep(5000);
        } catch (Exception e) {
            throw new Exception("Outlook 注册失败: " + e.getMessage(), e);
        } finally {
            driver.quit();
        }
    }
}
